<template>
    <section class="cicd-itemconfig">
        <el-form ref="configItemData" :model="configItemData" label-width="93px" :rules="configDeployTaskRules" size="small">
            <el-form-item label="项目名" required prop="name">
                <el-col :span="4">
                    <el-tag size="mini"> {{configItemData.name}}</el-tag>
                </el-col>

            </el-form-item>
            <el-form-item label="项目描述">
                <el-col :span="16">
                    <el-input v-model="configItemData.describe"  type="textarea" :rows="2"></el-input>
                </el-col>
            </el-form-item>
            <el-form-item label="git源码" required prop="giturl">
                <el-col :span="16">
                    <el-tag size="mini"> {{configItemData.giturl}}</el-tag>
                </el-col>
            </el-form-item>
            <el-form-item label="分支" required prop="branch">
                <el-col :span="4">
                    <el-input v-model="configItemData.branch"></el-input>
                </el-col>

            </el-form-item>

            <el-form-item label="代码环境" >
                <el-tag size="mini"> {{configItemData.codelang}}</el-tag>
            </el-form-item>

            <el-form-item label="编译" >
                <el-col :span="8">
                    <el-input v-model="configItemData.compile"></el-input>
                </el-col>

            </el-form-item>



            <el-form-item label="部署策略" required prop="deploymode">
                <el-tag size="mini" type="danger"> {{configItemData.deploymode}}</el-tag>
            </el-form-item>

            <div v-if="configItemData.deploymode === 'ansible'">

                <el-form-item label="服务器组" required prop="hosts">
                    <el-select v-model="configItemData.hosts" placeholder="请选择负载集群" @focus="chooseHosts">
                        <el-option
                                v-for="item in hostOptions"
                                :label="item.name"
                                :value="item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="Ansible-yaml"  prop="yamlSyntaxCheck"
                >
                    <el-col :span="16">
                        <edit-yaml ></edit-yaml>
                    </el-col>
                </el-form-item>


            </div>

            <div v-if="configItemData.deploymode === 'k8s'">
                <!--<el-form-item label="">-->
                <!--<el-tag type="success">Docker 配置</el-tag>-->
                <!--</el-form-item>-->
                <el-form-item label="image" prop="imageRule">
                    <el-row >
                        <el-col :span="12"><el-input v-model="configItemData.imageUrl" placeholder="Repositoriy:habor.company.net"></el-input></el-col>
                        <el-col :span="4">
                            <!--<el-input v-model="configItemData.imageVersion" placeholder="Version:latest "></el-input>-->
                            <el-select v-model="configItemData.imageTag" placeholder="tagPolicy" style="width: 100%">
                                <el-option
                                        label="DateTime"
                                        value="DateTime"

                                >
                                    <span style="float: left">DateTime</span>
                                    <span style="float: right; color: #8492a6; font-size: 10px">2006-01-02-15-04-05</span>
                                </el-option>
                                <el-option
                                        label="BuildNumber"
                                        value="BuildNumber"
                                        disabled
                                >
                                    <span style="float: left">BuildNumber</span>
                                    <span style="float: right; color: #8492a6; font-size: 10px">13</span>
                                </el-option>
                                <el-option
                                        label="latest"
                                        value="latest"
                                >
                                </el-option>
                            </el-select>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="Dockerfile" prop="DockerfileRule">
                    <el-col :span="16">
                        <edit-yaml ></edit-yaml>
                    </el-col>
                </el-form-item>
                <el-form-item label="Deployment" prop="deploymentYamlCheckRule">

                    <el-row >
                        <!--<span>无法更换模板</span>-->
                        <!--<el-col :span="4">-->
                            <!--<el-select v-model="configItemData.k8stemplate" placeholder="请选择活动区域" style="width: 100%" @change="editBtndisable = false">-->
                                <!--<el-option-group-->
                                        <!--v-for="group in k8sDeploymentTemplateOptions"-->
                                        <!--:key="group.label"-->
                                        <!--:label="group.label">-->
                                    <!--<el-option-->
                                            <!--v-for="item in group.options"-->
                                            <!--:label="item.label ? item.label : item.name"-->
                                            <!--:value="item.value ? item.value : item.path"-->
                                            <!--:disabled="item.disabled">-->
                                    <!--</el-option>-->
                                <!--</el-option-group>-->
                            <!--</el-select>-->
                        <!--</el-col>-->
                        <el-col :span="3"><el-button type="default" size="mini"  @click="editK8sDeploymentYaml" ><i class="el-icon-edit" style="color: red"></i> {{configItemData.name}}.yaml</el-button></el-col>
                        <el-dialog title="K8s-Deployment" :visible.sync="dialogK8sYamlFormVisible">
                            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 25}" v-model="K8sYamlContent">


                            </el-input>
                            <span style="color: red;font-size: 8px" v-if="K8sYamlContentErrorVisible">{{K8sYamlContentErrorMessage}}</span>
                            <div slot="footer" class="dialog-footer">
                                <el-button type="primary" @click="yamlRender">保 存</el-button>
                                <el-button @click="dialogK8sYamlFormVisible = false">取 消</el-button>

                            </div>
                        </el-dialog>


                    </el-row>
                </el-form-item>
            </div>

            <el-form-item>

                <el-button @click="saveItem('configItemData')" type="primary" >保存</el-button>
                <el-button @click="closeThisTab">取消</el-button>
            </el-form-item>
        </el-form>

    </section>
</template>
<script>
    import editYaml from '../../components/edit/edityaml300.vue'
    import { getHostList,getDeploymentTemplateLists,LoadTemplateFile,SaveDeployConfig,LoadWorkspaceFile } from '../../api/api'
    import $ from 'jquery' //引入jquery 检测输入yaml内容是否格式错误
    import jsyaml from  '../../assets/js/js-yaml.min'

    export default {
        props: {
            deployItem: Object,
        },
        data() {
            var yamlCheckPass = (rule, value, callback) => {

                var cm = $(".yamlcode300  .CodeMirror")[0].CodeMirror;  //怕多个codemirror引起的混乱
                var doc = cm.getDoc();
                let content = doc.getValue().toString()



                if (content.trim() === '') {
                    callback(new Error('请输入ansible-playbook yaml格式脚本内容'));
                } else {
                    try {
                        let dropcontent = jsyaml.load(content);
                        dropcontent= ""
                        callback()

                    }catch (e) {
                        callback(new Error('格式错误： ' + e.message));
                    }
                }

            };
            var imageCheck = (rule, value, callback) => {
                let self = this
                if (self.configItemData.imageUrl === '') {
                    callback(new Error('请输入image地址'));
                } else if (self.configItemData.imageVersion === '') {
                    callback(new Error('请选择镜像Tag'));
                } else {
                    callback()
                }

            };
            var DockerfileCheck = (rule, value, callback) => {

                var cm = $(".yamlcode300  .CodeMirror")[0].CodeMirror;  //怕多个codemirror引起的混乱
                var doc = cm.getDoc();
                let content = doc.getValue().toString().trim()

                if (content === '') {
                    callback(new Error('请输入Dockerfile'));
                } else {
                    callback()
                }

            };
            var deploymentYamlCheck = (rule, value, callback) => {
                let content = this.k8sYamlContent

                if (content === '') {
                    callback(new Error('请编辑模板'));
                } else {
                    try {
                        let dropcontent = jsyaml.load(content);
                        dropcontent= ""
                        callback()

                    }catch (e) {
                        callback(new Error('格式错误： ' + e.message));
                    }
                }

            };
            return {
                configItemData: {
                    name: '',
                    describe: "",
                    giturl: "",
                    branch: "",
                    codelang: "",  //为啥不能用"Jdk"
                    compile: "",


                    deploymode: 'ansible',
                    hosts: '',
                    options: [],
                    ansibleContent: "",  //ansible 部署


                    // k8stemplate: '',
                    // date1: '',
                    // date2: '',
                    // delivery: false,
                    // type: [],
                    // resource: '',
                    // desc: '',
                    imageUrl: "",
                    imageTag: "",
                    Dockerfile: "",
                    k8sYamlContent: "",
                },
                hostOptions:[],
                configDeployTaskRules: {

                    branch: [
                        { required: true, message: '请输入项目分支', trigger: 'blur' },
                    ],

                    hosts: [
                        { required: true, message: '请选择服务组', trigger: 'change' }
                    ],
                    yamlSyntaxCheck: [
                        { validator: yamlCheckPass, trigger: 'blur'}
                    ],

                    //k8s mode
                    imageRule: [
                        { required: true,validator: imageCheck, trigger: 'blur'}

                    ],
                    DockerfileRule: [
                        { validator: DockerfileCheck, trigger: 'blur'}
                    ],
                    deploymentYamlCheckRule: [
                        { validator: deploymentYamlCheck, trigger: 'blur'}
                    ],

                },
                k8sDeploymentTemplateOptions: [
                    {
                        label: 'Deployment Template',
                        options: []
                    } ],

                editBtndisable: true,
                dialogK8sYamlFormVisible: false,
                K8sYamlContent: "",

                K8sDeploymentYamlContent: "",
                dialogK8sDeploymentYamlFormVisible: false,

                K8sYamlContentErrorMessage: "",
                K8sYamlContentErrorVisible: false,

            }
        },
        methods: {
            saveItem(formName) {
                console.log("debug here")

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        var cm = $(".yamlcode300  .CodeMirror")[0].CodeMirror;  //怕多个codemirror引起的混乱
                        var doc = cm.getDoc();
                        this.configItemData.ansibleContent = doc.getValue().toString()
                        let itemparam = {}
                        if (this.configItemData.deploymode === "ansible") {
                            itemparam = {
                                name: this.configItemData.name,
                                deploymode: this.configItemData.deploymode,
                                describe: this.configItemData.describe,
                                giturl : this.configItemData.giturl,
                                branch : this.configItemData.branch,
                                codelang :this.configItemData.codelang,
                                compile : this.configItemData.compile,

                                hosts : this.configItemData.hosts,
                                yamlcontent: this.configItemData.ansibleContent

                            }
                        } else {
                            itemparam = {
                                name: this.configItemData.name,
                                deploymode: this.configItemData.deploymode,
                                describe: this.configItemData.describe,
                                giturl : this.configItemData.giturl,
                                branch : this.configItemData.branch,
                                codelang :this.configItemData.codelang,
                                compile : this.configItemData.compile,

                                imageUrl : this.configItemData.imageUrl,
                                imageTag: this.configItemData.imageTag,
                                dockerfileContent: doc.getValue().toString(),
                                yamlcontent: this.K8sYamlContent,

                            }
                        }


                        SaveDeployConfig(itemparam).then((res) => {
                            console.log(res.code)
                            if (res.code === 400) {
                                this.$message({
                                    message: "Warning: 保存失败 " + res.message ,
                                    type: 'success',
                                    duration: 1000,
                                });
                            }else {
                                this.$message({
                                    message: " 保存成功 "  ,
                                    type: 'success',
                                    duration: 1000,
                                });

                                this.$emit('close_tab')
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });






            },
            chooseHosts(){
                let self = this
                getHostList().then((res) => {
                        console.log(res.data.hosts)
                        self.hostOptions = res.data.hosts
                    }
                )
            },
            closeThisTab() {
                this.$emit('close_tab')
            },
            getAllDeploymentTemplate(){
                getDeploymentTemplateLists().then((res) => {
                        //this.ipALL = res.data.iplists
                        // console.log(res.data.path)
                        this.k8sDeploymentTemplateOptions[0].options = res.data.path
                        console.log(res.data.path)
                    }
                )
            },
            editK8sDeploymentYaml() { //远程加载模板文件
                let self = this
                let k8syamlpath =  self.deployItem.yamlpath + "/" + self.deployItem.name + ".yaml"
                // console.log(k8syamlpath)
                    console.log(self.K8sYamlContent)
                    if (self.K8sYamlContent.trim() === "") {
                        LoadTemplateFile(k8syamlpath).then((res) => {
                                //
                                self.K8sYamlContent = res

                            }

                        )
                    }


                self.dialogK8sYamlFormVisible = true
                self.K8sYamlContentErrorVisible = false

            },
            yamlRender() {
                let self = this
                self.K8sYamlContent = self.K8sYamlContent.replace(/image:.*\n?/,'image: {{projectImageUrl}}\n')
                try {
                    let dropcontent = jsyaml.load(self.K8sYamlContent);
                    dropcontent= ""
                    // self.K8sDeploymentYamlContent = self.K8sYamlContent    //只有渲染并检测语法成功后赋值
                    self.dialogK8sYamlFormVisible = false

                }catch (e) {
                    self.K8sYamlContentErrorVisible = true
                    self.K8sYamlContentErrorMessage = e.message
                }

            },
            clearDoc(){
                var cm = $(".yamlcode300  .CodeMirror")[0].CodeMirror;  //怕多个codemirror引起的混乱
                var doc = cm.getDoc();
                doc.setValue("")
            },
            loadYaml(path) { //远程加载模板文件

                console.log("test workspce path " , path)

                var cm = $(".yamlcode300  .CodeMirror")[0].CodeMirror;  //怕多个codemirror引起的混乱
                var doc = cm.getDoc();
                doc.setValue("")
                LoadWorkspaceFile(path).then((res) => {
                        doc.setValue(res)
                    }
                )

            },


        },
        mounted() {
            // console.log("this item is",this.deployItem)
            this.configItemData = this.deployItem
            let path= ""
            if (this.deployItem.deploymode === "ansible") {
                path = this.deployItem.yamlpath + "/" + this.deployItem.name + ".yaml"
            }else if (this.deployItem.deploymode === "k8s") {
                path = this.deployItem.yamlpath + "/"  + "Dockerfile"
            }

            this.loadYaml(path)
            this.getAllDeploymentTemplate();
            console.log("this.configItemData.options is ")
            // this.chooseHosts()

        },
        components: {
            editYaml,
        },

    }
</script>
<style>
    .cicd-itemconfig .hosts-select {
        margin-top:5px;
        margin-bottom:5px;
    }
    .cicd-itemconfig .el-dialog__body {
        padding: 10px 20px;
    }
</style>